//
//  SearchDetailViewController.m
//  Menu
//
//  Created by dllo on 15/7/6.
//  Copyright (c) 2015年 lijiangang. All rights reserved.
//

#import "SearchDetailViewController.h"

@interface SearchDetailViewController ()

@end

@implementation SearchDetailViewController

- (void)dealloc
{
    [_searchCollectionView release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"搜索结果";
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(170*WIDTH, 120*HEIGHT);
    flowLayout.sectionInset = UIEdgeInsetsMake(10*HEIGHT, 10*WIDTH, 10*HEIGHT, 10*WIDTH);
    flowLayout.minimumInteritemSpacing = 10*HEIGHT;
    flowLayout.minimumLineSpacing = 10*HEIGHT;
    
    self.searchCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, MyWidth, MyHeight - 64 - 49) collectionViewLayout:flowLayout];
    self.searchCollectionView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:self.searchCollectionView];
    [flowLayout release];
    [_searchCollectionView release];
    
    self.searchCollectionView.delegate = self;
    self.searchCollectionView.dataSource = self;
    
    [self.searchCollectionView registerClass:[SearchDetailCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    self.searchArray = [NSMutableArray array];
    [self.searchArray removeAllObjects];
    self.page = 1;
    [self.searchCollectionView addLegendFooterWithRefreshingBlock:^{
       
        self.page++;
        if (self.page >= self.maxPageNumber + 1)
        {
            [self.searchCollectionView.footer noticeNoMoreData];
        }
        else
        {
            [self downLoadData];
            [self.searchCollectionView.footer endRefreshing];
        }
    }];
    [self downLoadData];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0)
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void)downLoadData
{
    

    
    NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"`!@#$%^&*()_-+={}[]:;'<>,.?/1234567890·！@#￥%……&*（）——-+={}【】：；“”‘《》，。、？"];
    
    self.searchSth = [[self.searchSth componentsSeparatedByCharactersInSet: doNotWant]componentsJoinedByString:@""];
    self.searchSth = [self.searchSth stringByReplacingOccurrencesOfString:@"~" withString:@""];
    
    NSLog(@"------------%@",self.searchSth);
    NSLog(@"%ld",self.searchSth.length);
    if (self.searchSth.length == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"请重新输入" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
        
    }else{
        NSString *bodyStr = [NSString stringWithFormat:@"name=%@&page=%ld&pageRecord=10&is_traditional=0",self.searchSth , self.page];
        [AFNTool post:@"http://admin.izhangchu.com/HandheldKitchen/api/home/tblAssort!getDataList.do" Body:bodyStr HttpResult:JSON RequsetBodyStyle:StringBody success:^(id result) {
//            NSLog(@"%@",result);
            NSString *message = [result objectForKey:@"message"];
//            NSLog(@"------%@",message);
            if ([message isEqualToString:@"success"]) {
                NSMutableDictionary *beanDict = [result objectForKey:@"bean"];
                self.maxPageNumber = [[beanDict objectForKey:@"maxPageNumber"] integerValue];
                NSMutableArray *array = [result objectForKey:@"data"];
                for (NSMutableDictionary *dict in array)
                {
                    SearchDetailModel *searchModel = [[SearchDetailModel alloc] initWithDic:dict];
                    searchModel.materialId = [dict objectForKey:@"id"];
                    [self.searchArray addObject:searchModel];
                    [searchModel release];
                }
                if (self.searchArray.count > 0) {
                    [self.searchArray removeObjectAtIndex:0];
                }
                [self.searchCollectionView reloadData];
            }else{
                
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"请重新输入" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];
                [alert release];
            }
        } failure:^(NSError *error) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"网络错误" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            [alert release];
        }];
    }
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.searchArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    SearchDetailCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    cell.searchModel = [self.searchArray objectAtIndex:indexPath.item];
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    SearchDetailModel *searchDetailModel = [self.searchArray objectAtIndex:indexPath.item];
    if ([searchDetailModel.type isEqualToString:@"1"])
    {
        CookingViewController *cookingVC = [[CookingViewController alloc] init];
        cookingVC.imagePathThumbnails = searchDetailModel.imagePath;
        cookingVC.foodName = searchDetailModel.name;
        cookingVC.vegetable_id = searchDetailModel.materialId;
        [self.navigationController pushViewController:cookingVC animated:YES];
    }
    if ([searchDetailModel.type isEqualToString:@"4"])
    {
        PayFoodViewController *payFoodVC = [[PayFoodViewController alloc] init];
        payFoodVC.payFoodId = searchDetailModel.materialId;
        payFoodVC.payFoodName = searchDetailModel.name;
        [self.navigationController pushViewController:payFoodVC animated:YES];
    }
}




































- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
